<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="tableList" class="-mt-10px">
      <el-table-column v-if="props.type" label="序号" type="index" width="100" />
      <el-table-column label="序列号" min-width="360" v-if="props.type">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.serialNo`" :rules="formRules.serialNo" class="mb-0px!">
            <el-input v-model="row.serialNo" :disabled="row.readonly" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="物料编号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.itemCode`" :rules="formRules.itemCode" class="mb-0px!">
            <!-- <el-input v-model="row.itemCode" readonly /> -->
            {{ row.itemCode }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="物料名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.itemName`" :rules="formRules.itemName" class="mb-0px!">
            <!-- <el-input v-model="row.itemName" readonly /> -->
            {{ row.itemName }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="物料规格" min-width="350">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.itemSpecification`"
            :rules="formRules.itemSpecification"
            class="mb-0px!"
          >
            <!-- <el-input v-model="row.itemSpecification" readonly /> -->

            <el-tooltip
              class="item"
              effect="dark"
              :content="row.itemSpecification"
              placement="top-start"
            >
              <div class="lineText"> {{ row.itemSpecification }}</div>
            </el-tooltip>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="纤盘号" min-width="150" v-if="props.type">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.fiberPalletNo`"
            :rules="formRules.fiberPalletNo"
            class="mb-0px!"
          >
            <!-- <el-input v-model="row.fiberPalletNo" readonly /> -->
            {{ row.fiberPalletNo }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.qty`" :rules="formRules.qty" class="mb-0px!">
            <el-input
              v-model="row.qty"
              v-if="props.type"
              type="number"
              :disabled="row.readonly"
              @input="changeVal(row)"
              v-numberRange="{ min: 0, max: row.max, precision: 1 }"
            />
            <div v-else>{{ row.qty }}</div>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="已消耗" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.consumedQty`"
            :rules="formRules.consumedQty"
            class="mb-0px!"
          >
            <!-- <el-input v-model="row.consumedQty" readonly /> -->
            {{ row.consumedQty }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unit`" :rules="formRules.unit" class="mb-0px!">
            <!-- <el-input v-model="row.unit" readonly /> -->
            {{ row.unit }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" v-if="props.type" width="150" fixed="right" label="操作">
        <template #default="{ row, $index }">
          <el-button link type="primary" v-if="row.id">
            <span
              v-if="row.isEditing"
              :style="{ color: row.isEditing ? '' : '#ccc' }"
              @click="handleAdd(row)"
              >分盘</span
            >
            <span v-else :style="{ color: row.isEditing ? '' : '#ccc' }">分盘</span>
          </el-button>
          <el-button link type="primary" v-if="row.id && row.materialType != 0">
            <span
              v-if="row.isEditing"
              :style="{ color: row.isEditing ? '' : '#ccc' }"
              @click="handleAddNew(row)"
            >生成新序列号</span
            >
            <span v-else :style="{ color: row.isEditing ? '' : '#ccc' }">生成新序列号</span>
          </el-button>
          <el-button link type="primary" @click="handleDelete(row, $index)" v-else-if="!row.id">--</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
</template>
<script setup lang="ts">
const props = defineProps<{
  docNo: undefined // 工单号（主表的关联字段）
  tableList: []
  type: undefined
  selmaterialType: undefined
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const colorStyle = computed(() => {
  return
})

const vNumberRange = {
  updated(el, binding) {
    // 获取最大值和最小值
    const { min, max } = binding.value
    // 添加 input 事件监听器
    el.addEventListener('input', (event) => {
      let value = event.target.value
      // 如果是空字符串，不做处理
      if (value === '') return
      // 尝试将值转换为数字
      const numValue = parseFloat(value)
      // 如果转换失败，清空输入
      if (isNaN(numValue)) {
        event.target.value = ''
        return
      }
      // 如果值小于最小值，设置为最小值
      if (min !== undefined && numValue < min) {
        event.target.value = min
      }
      // 如果值大于最大值，设置为最大值
      if (max !== undefined && numValue > max) {
        event.target.value = max
      }
    })
  }
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
// watch(
//   () => props.docNo,
//   async (val) => {
//     // 1. 重置表单
//     formData.value = []
//     // 2. val 非空，则加载数据
//     if (!val) {
//       return;
//     }
//     try {
//       formLoading.value = true
//       // 物料详情
//       formData.value = await MaterialApi.getMaterialByDocNo(val)
//       // 已领用详情
//       formData.value = await MaterialUsageApi.getMaterialUsageByDocNo(val)
//     } finally {
//       formLoading.value = false
//     }
//   },
//   { immediate: true }
// )

// const tableListCopy = ref(JSON.parse(JSON.stringify(props.tableList)))
/** 新增按钮操作 */

const emit = defineEmits(['update-data', 'put-data', 'delete-data'])

const fIndex = ref(0)
const message = useMessage()

const handleAdd = (item) => {
  if (item.qty <= 1) {
    message.error('分盘数量小于2')
    return
  }

  console.log('row',item)

  if(item.consumedQty >= item.qty){
    message.error('已消耗数量大于分盘数量')
    return
  }

  const row = {
    docNo: props.docNo,
    serialNo: `${item.serialNo}-${(fIndex.value += 1)}`,
    itemCode: item.itemCode,
    itemName: item.itemName,
    itemSpecification: item.itemSpecification,
    fiberPalletNo: item.fiberPalletNo,
    qty: 0,
    consumedQty: null,
    unit: item.unit,
    parentId: item.id,
    materialType: props.selmaterialType,
    max: parseInt(item.qty - item.consumedQty),
    batchNo: item.batchNo
  }
  emit('update-data', row)
}

const handleAddNew = (item) => {
  const row = {
    docNo: props.docNo,
    serialNo: `${item.serialNo}-${(fIndex.value += 1)}`,
    itemCode: item.itemCode,
    itemName: item.itemName,
    itemSpecification: item.itemSpecification,
    fiberPalletNo: item.fiberPalletNo,
    qty: 0,
    consumedQty: null,
    unit: item.unit,
    parentId: item.id,
    materialType: props.selmaterialType,
    max: 0,
    batchNo: item.batchNo
  }
  emit('update-data', row)
}

/** 删除按钮操作 */
const handleDelete = (row, index) => {
  console.log(index)

  emit('delete-data', row, index)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

const changeVal = (val) => {
  val.qty > val.max ? (val.qty = val.max) : val.qty
  val.qty < 0 ? (val.qty = 0) : val.qty

  emit('put-data', val)
}

defineExpose({ validate, getData })
</script>
<style>
.lineText {
  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 文字溢出隐藏 */
  text-overflow: ellipsis; /* 出现省略号 */
}
</style>
